// pages/submit-order/submit-order.js
var http = require("../../utils/http.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popupShow: false,
    couponSts: 1,
    couponList: [],
    // 订单入口 0购物车 1立即购买
    orderEntry: "0",
    userAddr: null,
    orderItems: [],
    coupons: {
      totalLength: 0,
      canUseCoupons: [],
      noCanUseCoupons: []
    },
    couponNums: 0,
    actualTotal: 0,
    total: 0,
    totalCount: 0,
    transfee: 0,
    reduceAmount: 0,
    remark: "",
    couponIds: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      orderEntry: options.orderEntry,
      couponNums: 0
    });
    // wx.showLoading();
    // var page = this
    // var couponPar = {
    //     url: "/p/coupon/getTtlCoupons",
    //     method: "GET",
    //     callBack: function(res) {
    //         wx.hideLoading();
    //         console.log(res)
    //         page.setData({
    //             'coupons.canUseCoupons': res
    //         })
    //     }
    // }
    // http.request(couponPar);
  },

  //加载订单数据
  loadOrderData: function() {
    var addrId = 0;
    if (this.data.userAddr != null) {
      addrId = this.data.userAddr.addrId;
    }
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/confirm",
      method: "POST",
      data: {
        addrId: addrId,
        orderItem: this.data.orderEntry === "1" ? JSON.parse(wx.getStorageSync("orderItem")) : undefined,
        basketIds: this.data.orderEntry === "0" ? JSON.parse(wx.getStorageSync("basketIds")) : undefined,
        couponIds: this.data.couponIds,
        userChangeCoupon: 1
      },
      callBack: res => {
        wx.hideLoading();
        let orderItems = [];

        res.shopCartOrders[0].shopCartItemDiscounts.forEach(itemDiscount => {
          orderItems = orderItems.concat(itemDiscount.shopCartItems)
        })
        if (res.shopCartOrders[0].coupons) {
          let canUseCoupons = []
          let unCanUseCoupons = []
          res.shopCartOrders[0].coupons.forEach(coupon => {
            if (coupon.status) {
                if ( res.shopCartOrders[0].total < coupon.minThres){
                    coupon.text = '未达到使用限额'
                    unCanUseCoupons.push(coupon)
                }
                else {
                    coupon.text = ''
                    canUseCoupons.push(coupon)
                }
                
            } else {
                var endDate = new Date(coupon.endDate);
                var now = new Date();
                if (endDate < now){
                    coupon.text = '该券已过期'
                }
                else{
                    coupon.text = '该券已使用'
                }
                unCanUseCoupons.push(coupon)
              }
          })
          this.setData({
            coupons: {
              totalLength: res.shopCartOrders[0].coupons.length,
              canUseCoupons: canUseCoupons,
              unCanUseCoupons: unCanUseCoupons
            }
          })
        }

        this.setData({
          orderItems: orderItems,
          actualTotal: res.actualTotal,
          total: res.total,
          totalCount: res.totalCount,
          userAddr: res.userAddr,
          transfee: res.shopCartOrders[0].transfee,
          shopReduce: res.shopCartOrders[0].shopReduce,
        });
      },
      errCallBack: res => {
        wx.hideLoading();
        this.chooseCouponErrHandle(res)
      }
    };
    http.request(params);

  },

  /**
   * 优惠券选择出错处理方法
   */
  chooseCouponErrHandle(res) {
    // 优惠券不能共用处理方法
    if (res.statusCode == 601) {
      wx.showToast({
        title: res.data,
        icon: "none",
        duration: 3000,
        success: res => {
          this.setData({
            couponIds: []
          })
        }
      })
      setTimeout(() => {
        this.loadOrderData();
      }, 2500)
    }
  },

  onRemarksInput: function (e) {
    this.setData({
      remarks: e.detail.value
    });
  },

  /**
   * 提交订单
   */
  toPay: function() {
    if (!this.data.userAddr) {
      wx.showToast({
        title: '请选择地址',
        icon: "none"
      })
      return;
    }

    this.submitOrder();
  },


  submitOrder: function() {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/submit",
      method: "POST",
      data: {
        orderShopParam: [{
          remarks: this.data.remark,
          shopId: 1
        }]
      },
      callBack: res => {
        wx.hideLoading();
        // this.calWeixinPay(res.orderNumbers);
        this.normalPay(res.orderNumbers);
      }
    };
    http.request(params);
  },

  normalPay: function(orderNumbers) {
    wx.showLoading({
        mask: true
    });
    var params = {
        url: "/p/order/normalPay",
        method: "POST",
        data: {
            payType: 2,
            orderNumbers: orderNumbers
        },
        callBack: function(res) {
            console.log(res)
            if (res) {
                // console.log("支付成功");
                wx.navigateTo({
                url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
                })
            }
            else {
                wx.navigateTo({
                url: '/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
                })
            }
        }
    }
    http.request(params);      
  },
  /**
   * 唤起微信支付
   */
  calWeixinPay: function(orderNumbers) {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/pay",
      method: "POST",
      data: {
        payType: 1,
        orderNumbers: orderNumbers
      },
      callBack: function(res) {
        wx.hideLoading();
        wx.requestPayment({
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.packageValue,
          signType: res.signType,
          paySign: res.paySign,
          success: e => {
            // console.log("支付成功");
            wx.navigateTo({
              url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
            })
          },
          fail: err => {
            wx.navigateTo({
              url: '/pages/pay-result/pay-result?sts=0&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
            })
          }
        })

      }
    };
    http.request(params);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.selAddress == "yes") {
      this.setData({ //将携带的参数赋值
        userAddr: currPage.data.item
      });
    }
    //获取订单数据
    this.loadOrderData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  changeCouponSts: function(e) {
    this.setData({
      couponSts: e.currentTarget.dataset.sts
    });
  },

  showCouponPopup: function() {
    console.log(this.data.coupons.canUseCoupons)
    this.setData({
      popupShow: true
    });
  },

  closePopup: function() {
    this.setData({
      popupShow: false
    });
  },

  /**
   * 去地址页面
   */
  toAddrListPage: function() {
    wx.navigateTo({
      url: '/pages/delivery-address/delivery-address?order=0',
    })
  },
  /**
   * 确定选择好的优惠券
   */
  choosedCoupon: function() {
    this.loadOrderData();
    this.setData({
      popupShow: false,
      ['coupons.totalLength']: this.data.couponIds.length,
      couponNums: this.data.couponIds.length
    }, function() {
        // 数据更新完成后的操作
        console.log(this.data.couponIds.length)
    });
  },

  /**
   * 优惠券子组件发过来
   */
//   checkCoupon: function(e) {
//     var ths = this;
//     let index = ths.data.couponIds.indexOf(e.detail.couponId);
//     if (index === -1) {
//       ths.data.couponIds.push(e.detail.couponId)
//     } else {
//       ths.data.couponIds.splice(index, 1)
//     }
//     console.log(this.data.couponIds)
//     this.data.couponIds.forEach(index => {
//         // 检查索引是否在canUseCoupons数组的范围内
//         if (index >= 0 && index < this.data.coupons.canUseCoupons.length) {
//           // 将对应元素减1
//           this.data.coupons.canUseCoupons[index].choose = true;
//         }
//     });
//     console.log(this.data.coupons.canUseCoupons)
//   },
    checkCoupon: function(e) {
        var ths = this;
        let index = ths.data.couponIds.indexOf(e.detail.couponId);
        let updatedCouponIds = [...ths.data.couponIds]; // 创建couponIds的副本以进行更新
        let updatedCanUseCoupons = [...ths.data.coupons.canUseCoupons]; // 创建canUseCoupons的副本以进行更新
    
        // 根据e.detail.couponId更新updatedCouponIds
        if (index === -1) {
            updatedCouponIds.push(e.detail.couponId);
        } else {
            updatedCouponIds.splice(index, 1);
        }
    
        // 根据updatedCouponIds更新updatedCanUseCoupons中的choose属性
        updatedCanUseCoupons.forEach((item, idx) => {
            if (updatedCouponIds.includes(item.couponId)) {
                updatedCanUseCoupons[idx] = { ...item, choose: true };
            }
            else {
                updatedCanUseCoupons[idx] = { ...item, choose: false };
            }
        });
    
        // 使用setData更新数据，并在回调中处理依赖于数据更新的操作
        ths.setData({
        'couponIds': updatedCouponIds,
        'coupons.canUseCoupons': updatedCanUseCoupons
        }, function() {
            // 数据更新完成后的操作
            console.log('更新后的couponIds:', ths.data.couponIds);
            console.log('更新后的canUseCoupons:', ths.data.coupons.canUseCoupons);
        })
    },
  
})